/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import router from '@system.router';
import prompt from '@system.prompt';
//import socket from '@ohos.net.socket';
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility';
import http from '@ohos.net.http';

const titles = [
    {
        'name': 'All'
    },

];

const chatData = [
    {
        'title': '账号',
        'topMessage': '欢迎来到华为鸿蒙操作系统',
        'imgUrl': '/common/images/sessionPic/img_8.png',
        'readTime': '17:00',
        'unRead': '8',
    },
    {
        'title': '密码',
        'topMessage': '吃了没有?',
        'imgUrl': '我叫学习',
        'readTime': '17:00',
        'unRead': '4',
    },

];
const personData = {
    'name': '我叫学习',
    'personNum': '萌聊号:133213321',
    'imgUrl': '/common/images/sessionPic/img_7.png',
}

const Gtalk = [
    {
        text: 'username001',
        imgUrl: 'common/images/personPic/1.png',
    },
    {
        text: 'username002',
        imgUrl: 'common/images/personPic/1.png',
    },
    {
        text: 'username003',
        imgUrl: 'common/images/personPic/1.png',
    },
];

export default {
    data: {
        GtalkList: Gtalk,
        titleList: titles,
        chatList: chatData,
        person:personData,
        // 滑动拼图验证的图片列表
        swipeImgList: [
            '/common/images/swipePuzzle/test1.jpg',
            '/common/images/swipePuzzle/test2.jpg',
            '/common/images/swipePuzzle/test3.jpg',
            '/common/images/swipePuzzle/test4.jpg',
            '/common/images/swipePuzzle/test5.jpg',
            '/common/images/swipePuzzle/test6.jpg',
            '/common/images/swipePuzzle/test7.jpg',
            '/common/images/swipePuzzle/test8.jpg'
        ],
        // 旋转拼图验证的图片列表
        rotateImgList: [
            '/common/images/swipePuzzle/test1.jpg',
            '/common/images/swipePuzzle/test2.jpg',
            '/common/images/swipePuzzle/test3.jpg',
            '/common/images/swipePuzzle/test4.jpg',
            '/common/images/swipePuzzle/test5.jpg',
            '/common/images/swipePuzzle/test6.jpg',
            '/common/images/swipePuzzle/test7.jpg',
            '/common/images/swipePuzzle/test8.jpg'
        ],
        // 滑动拼图验证的参数
        swipePuzzleTestAttrs: {
            width: 300,
            height: 225,
            blockSize: 50
        },
        // 旋转拼图验证的参数
        rotatePuzzleTestAttrs: {
            width: 300,
            height: 225,
            radius: 100
        },
        title: "",
        username: "",
        password: "",
        checkState: false,
        rotateState:false,
        response:'',
        token:'111',
        returnValue:'',
        path:"",
        addToken:"111",
        result:"111",
        code:"111",
        header:"111",
        user:{
            code:"",
            msg:"",
            data:""
        },
    },
    onInit() {
        this.title = this.$t('strings.title');
        //取token
       /* let storage = dataStorage.getStorageSync(this.path);
        console.log("this.path " + this.path);
        storage.putSync('startup','auto');
        storage.flushSync()
        let result = storage.getSync('startup','00')
        console.log("result " + result)*/
    },

    onCreate(){
        //libsocket自带的接收
//        this.$app.$def.mysocket.connect("192.168.1.110",7777);
//        console.info("Application onCreate");
    },
   /* onDestroy(){
        this.$app.$def.mysocket.close();
    },*/
    onShow(){
        //this.autoLoginForTest() //为了真机调试寻找bug时节省时间，自动登录账号，正式版需要将此行注释掉
    },
    // 事件处理函数，在此处定义验证完成后的操作
    onResReceived(e) {
        prompt.showToast({
            message: "父组件得到结果:" + e.detail.result
        });
        this.rotateState = e.detail.result;
        console.info("login====>rotateState: " + this.rotateState)
    },
    // 监听密码输入框中数据信息的变化
    change2(e) {
        this.password = e.value;
    },
    checkboxOnChange(e) {
        this.checkState = e.checked;
    },

    getToken(){
        var context = featureAbility.getContext()
        context.getFilesDir().then(v =>{
            dataStorage.getStorage(v + '/smart_build').then(it =>{
                let promise = it.get("token","default")
                promise.then((value) => {
                    console.info("login====>tokenvalue " + value)
                    this.addToken = value
                }).catch((err) => {
                    console.info("login====>token failed with err: " + err)
                })
            })
        })
    },

    clickCustomType(str) {
        console.log("login====>clickCustomType(str):"+str)
    },
    clickCustomType3(str) {
        console.log("login====>clickCustomType3(str):"+str)
        router.push({ // 页面跳转进入注册
            uri: "pages/login/register/register",
            params: this.username + "-" + this.password
        })
    },
    /*
     * 存token到storage
     */
    setStorage(){
        //test
        var context = featureAbility.getContext()
         context.getFilesDir().then(v =>{
             dataStorage.getStorage(v + '/smart_build').then(it =>{
                 console.info("login====>context.getFilesDir successfully.it:" + it)
                 console.error("login====>response.token:" + this.token)
                 it.put('token', this.token)
                     .then(() =>{
                         console.info("login====>token success")
                         it.flush()
                         let result = it.getSync('token','00')
                         console.error("login====>result：" + result)
                     }).catch((err) =>{
                     console.error("login====>保存token失败err：" + err)
                 })
             })
         }).catch((err) =>{
             console.error("login====>context.getFilesDir failed with err：" + err)
         })
    },
    closePanel() {
        this.$element('simplepanel').close()
    },
    /**
     * 确认点击操作
     */
    checkClick(){
        //response的响应返回是否验证成功！！
        console.info('login====>returnValue :' + this.returnValue + "rotateState : " +this.rotateState);
        if(this.returnValue == '200' && this.rotateState == true){
            //token存入
            this.setStorage()
            prompt.showToast({
                message: '登录成功！',
                duration: 2000,
            });
            console.info('login====>sessionList onReady')
            router.push({ // 页面跳转进入列表刷新
                uri: "pages/index/index",
            })
        }else{
            prompt.showToast({
                message: '登录失败！',
                duration: 2000,
            });
        }
    },
    /**
     * 登录点击操作
     */
    loginClick(){
        this.setStorage();
        this.username = this.$app.$def.uid;
       /* router.push({ // 页面跳转进入列表刷新
            uri: "pages/index/index",
        })*/
        if (!this.checkState) {
            console.log('login====>请阅读服务协议与隐私保护')
            return;
        }
        //记忆账号持久化
        var index = this.$app.$def.memory.findIndex(item => {return item.text == this.username})
        console.info("login====>index: " + index)
        if(this.$app.$def.memory.findIndex(item => {return item.text == this.username}) == -1){
            this.$app.$def.memory.push({
                text: this.username,
                imgUrl: 'common/images/personPic/1.png',
            })
        }

        console.info('login====>this.username: ' + this.username);
        //弹出弹窗
        this.$element('simplepanel').show()

        prompt.showToast({
            message: '发送开始！',
            duration: 2000,
        });
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/login", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.username,"password":this.password}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            prompt.showToast({
                message: '发送成功！',
                duration: 2000,
            });
            console.info('login====>value.result: ' + value.result);
            this.user = JSON.parse(value.result.toString())
            this.token = this.user.data;
            this.returnValue = this.user.code;
            console.info('login====>value.responseCode: ' + value.responseCode);
            console.info('login====> value.header: ' + value.header);
        }).catch((err) => {
            console.error(`login====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    autoLoginForTest(){
        this.username = '1';
        this.$app.$def.uid = this.username;
        this.password = '12345';
        this.checkState = true;
        this.loginClick();
        this.returnValue = '200';
        this.rotateState = true;
        this.checkClick()
    },
}



